package engine;

import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import engine.controllers.Keyboard;
import engine.entities.Entity;
import engine.entities.EntityFactory;
import engine.render.Render;

public class Game extends TimerTask {
	static final int FPS = 60;
	static final float DELTA = (float)1/FPS;
	LinkedList<Entity> entities;
	Render render;

	public Game() {
		entities = new LinkedList<Entity>();
		render = new Render(800, 600);
	}

	public boolean addEntity(Entity e) {
		return entities.add(e);
	}

	public boolean removeEntity(Entity e) {
		return entities.remove(e);
	}

	public void beginGame() {
		render.setVisible(true);
	}

	private void mainLoop() throws InterruptedException {
		render.clear();
		for (Entity e : entities) {
			e.updatePhysics(DELTA);
			e.updateController(DELTA);
			e.updatePosition();
			calculateCollisions(e);
			render.draw(e);
			if (e.getEnergy().getValue() < 0) {
				entities.remove(e);
			}
		}
	}

	private void calculateCollisions(Entity a) {
		for (Entity b : entities) {
			a.updateCollisions(b);
		}
	}

	public Keyboard getInput() {
		return render.getKeyboardController();
	}

	@Override
	public void run() {
		try {
			mainLoop();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
	
	public static void main(String[] args) {
		Game g = new Game();
		Timer timer = new Timer();
		EntityFactory factory = new EntityFactory();
		Keyboard controller = g.getInput();
		g.addEntity(factory.createGumba(800 * 2 / 3, 600 / 2));
		g.addEntity(factory.createPlayer(controller, 800 * 1 / 3, 600 / 2));
		g.beginGame();
		timer.scheduleAtFixedRate(g,0,1000/FPS);
	}

	

}
